import torch
from torch import nn
from torchvision.models import vgg16_bn
import os
import struct

def main():
    print('cuda device count: ', torch.cuda.device_count())
    # net = torch.load('./weights/best.pth')
    net = vgg16_bn(pretrained=True).to('cuda:0')
    net.classifier=nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 10),
        ).to('cuda:0')
    print(net)

    torch.save({'model_state_dict': net.state_dict()},'weights/best.pth')
    # new_model_state_dict={}
    # for k,v in torch.load('./weights/best.pth')["model_state_dict"].items():
    #     new_model_state_dict[k[7:]]=v
    # net.load_state_dict(new_model_state_dict)
    net.eval()

    #print('model: ', net)
    #print('state dict: ', net.state_dict()['conv1.weight'])
    tmp = torch.ones(1, 3, 224, 224).to('cuda:0')
    #print('input: ', tmp)
    out = net(tmp)
    print('VGG out:', out)

    f = open("VGG16.wts", 'w')
    f.write("{}\n".format(len(net.state_dict().keys())))
    for k,v in net.state_dict().items():
        #print('key: ', k)
        #print('value: ', v.shape)
        vr = v.reshape(-1).cpu().numpy()
        f.write("{} {}".format(k, len(vr)))
        for vv in vr:
            f.write(" ")
            f.write(struct.pack(">f", float(vv)).hex())
        f.write("\n")

if __name__ == '__main__':
    main()

